<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/djean/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/djean/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/djean/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/djean/images/logo.svg" color="#222">

<link rel="stylesheet" href="/djean/css/main.css">


<link rel="stylesheet" href="/djean/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/djean/',
    scheme: 'Pisces',
    version: '7.5.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="什么是单例模式单例模式是指：保证一个类仅有一个实例，并提供一个访问它的全局访问点要实现一个标准的单例模式，无非就是用一个变量赖标志当前是否已经为某个类创建过对象，如果是，则在下一次返回该类的实例时，直接返回之前创建的对象即可。代码如下： 12345678910111213var Singleton = function (name) &amp;#123;    this.name = name;&amp;#125">
<meta name="keywords" content="JavaScript">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript设计模式之单例模式">
<meta property="og:url" content="https:&#x2F;&#x2F;djiangogo.gitee.io&#x2F;2019&#x2F;11&#x2F;24&#x2F;singleton-pattern&#x2F;index.html">
<meta property="og:site_name" content="djean的个人博客">
<meta property="og:description" content="什么是单例模式单例模式是指：保证一个类仅有一个实例，并提供一个访问它的全局访问点要实现一个标准的单例模式，无非就是用一个变量赖标志当前是否已经为某个类创建过对象，如果是，则在下一次返回该类的实例时，直接返回之前创建的对象即可。代码如下： 12345678910111213var Singleton = function (name) &amp;#123;    this.name = name;&amp;#125">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-11-26T11:33:03.282Z">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://djiangogo.gitee.io/2019/11/24/singleton-pattern/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>JavaScript设计模式之单例模式 | djean的个人博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/djean/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">djean的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/djean/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/djean/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/djean/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/djean/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/djean/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://djiangogo.gitee.io/djean/2019/11/24/singleton-pattern/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/djean/images/avatar.png">
      <meta itemprop="name" content="djean">
      <meta itemprop="description" content="时刻保持一个上进心">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="djean的个人博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          JavaScript设计模式之单例模式
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-11-24 21:51:14" itemprop="dateCreated datePublished" datetime="2019-11-24T21:51:14+08:00">2019-11-24</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-11-26 19:33:03" itemprop="dateModified" datetime="2019-11-26T19:33:03+08:00">2019-11-26</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/djean/categories/javascript%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" itemprop="url" rel="index">
                    <span itemprop="name">javascript设计模式</span>
                  </a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="什么是单例模式"><a href="#什么是单例模式" class="headerlink" title="什么是单例模式"></a>什么是单例模式</h2><p>单例模式是指：保证一个类仅有一个实例，并提供一个访问它的全局访问点<br>要实现一个标准的单例模式，无非就是用一个变量赖标志当前是否已经为某个类创建过对象，如果是，则在下一次返回该类的实例时，直接返回之前创建的对象即可。代码如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> Singleton = <span class="function"><span class="keyword">function</span> (<span class="params">name</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.name = name;</span><br><span class="line">&#125;</span><br><span class="line">Singleton.instance = <span class="literal">null</span>;</span><br><span class="line">Singleton.prototype.getname = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.name);</span><br><span class="line">&#125;</span><br><span class="line">Singleton.getInstance = <span class="function"><span class="keyword">function</span> (<span class="params">name</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!<span class="keyword">this</span>.instance) &#123;</span><br><span class="line">        <span class="keyword">this</span>.instance = <span class="keyword">new</span> Singleton(name);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.instance</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里跟我们以往new一个构造函数的方式来获取一个对象不同，这里需要使用Singleton.getInstance的方式来获取。<br>接下来我们来实现一个“透明”的单例类，用户从这个类中创建对象的时候，可以像使用其他任何类一样，new一下就行了。如下例子是使用createDiv单例类在页面中创建唯一的div节点，代码如下:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> CreateDiv = (<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> instance;</span><br><span class="line">    <span class="keyword">var</span> CreateDiv = <span class="function"><span class="keyword">function</span> (<span class="params">html</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (instance) &#123;</span><br><span class="line">            <span class="keyword">return</span> instance;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">this</span>.html = html;</span><br><span class="line">        <span class="keyword">this</span>.init();</span><br><span class="line">        <span class="keyword">return</span> instance = <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    CreateDiv.prototype.init = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> div = <span class="built_in">document</span>.createElement(<span class="string">'div'</span>);</span><br><span class="line">        div.innerHTML = <span class="keyword">this</span>.html;</span><br><span class="line">        <span class="built_in">document</span>.body.appendChild(div);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> CreateDiv;</span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure>
<p>但是上面的代码，给读者增加了一下阅读难度，这里为了把instance封装起来，使用了自执行的匿名函数和闭包，并且让这个匿名函数返回真正的Singleton构造方法。<br>仔细看上面的CreateDiv类，它实际上是负责了两件事，第一件是创建对象和执行初始化，第二件是保证只有一个对象。这就违反了单一职责原则了。我们可以用代理的方式来解决这个问题。这里不做过多介绍。</p>
<h2 id="JavaScript中的单例模式"><a href="#JavaScript中的单例模式" class="headerlink" title="JavaScript中的单例模式"></a>JavaScript中的单例模式</h2><p>上面提到的几种单例模式，更多的是接近传统的面向对象语言中的实现，单例对象从类中而来，在以类为中心的语言中，比如java，如果需要某个对象，就必须先定义一个class类。<br>但是js其实是一门无类的语言，在这里生搬硬套单例模式的概念，似乎意义不大，总之，单例模式的核心就是确保只有一个实例，并且提供全局访问。这样说来，我们在js中经常使用的全局变量貌似是单例模式。但是全局变量很容易造成全局污染，在大型项目中，如果不对全局变量加以限制和管理，很容易出现不可预估的后果。我们可以通过使用命名空间和变量私有化来降低全局变量带来的命名污染。</p>
<h2 id="惰性单例"><a href="#惰性单例" class="headerlink" title="惰性单例"></a>惰性单例</h2><p>惰性单例是单例模式的重点，惰性单例值得是在需要的时候，才会去创建对象实例<br>回头看看我们前面写的CreateDiv类，如果现在我需要往页面添加script标签，用来跨域请求数据，这时就必须如法炮制，把CreateDiv抄一遍，这样做当然是不好的。<br>我们需要把不变的部分隔离出来，看一看单例模式的实现过程，发现管理单例的逻辑其实是完全可以抽象出来的，这个逻辑始终是一样的：用一个变量标志是否创建过对象，如果是，则在下次直接返回已经创建好的对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> getSingle = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> result;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> result || (result = fn.apply(<span class="keyword">this</span>, <span class="built_in">arguments</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样我们只需要将创建div的方法用参数fn的形式传入getSingle，除此之外，我们还可以传createScript、cerateIframe等，之后再让getSingle返回一个新的函数，并且用一个变量result来保存fn的计算结果。result变量因为身在闭包中，它永远不会被销毁。在将来的请求中，如果result已经赋值了，那么它就会返回这个值。</p>
<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p>单例模式是我们学习的第一个模式，我们先学习了传统的单例模式实现，也了解到因为语言的差异性，有更合适的方法在JavaScript中创建单例。惰性单例技术，是在合适的时候才创建对象，并且只创建唯一的一个，在实现的时候，将创建对象和管理单例的职责分布在两个不同的方法中，这个才是精髓。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/djean/tags/JavaScript/" rel="tag"># JavaScript</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
                <a href="/djean/2019/11/25/proxy-pattern/" rel="prev" title="JavaScript设计模式之代理模式">
                  JavaScript设计模式之代理模式 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是单例模式"><span class="nav-number">1.</span> <span class="nav-text">什么是单例模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JavaScript中的单例模式"><span class="nav-number">2.</span> <span class="nav-text">JavaScript中的单例模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#惰性单例"><span class="nav-number">3.</span> <span class="nav-text">惰性单例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#小结"><span class="nav-number">4.</span> <span class="nav-text">小结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <img class="site-author-image" itemprop="image" alt="djean"
    src="/djean/images/avatar.png">
  <p class="site-author-name" itemprop="name">djean</p>
  <div class="site-description" itemprop="description">时刻保持一个上进心</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/djean/archives/">
        
          <span class="site-state-item-count">2</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/djean/categories/">
          
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/djean/tags/">
          
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">djean</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.0.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.5.0
  </div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/djean/lib/anime.min.js"></script>
  <script src="/djean/lib/velocity/velocity.min.js"></script>
  <script src="/djean/lib/velocity/velocity.ui.min.js"></script>
<script src="/djean/js/utils.js"></script><script src="/djean/js/motion.js"></script>
<script src="/djean/js/schemes/pisces.js"></script>
<script src="/djean/js/next-boot.js"></script>



  
















  

  

</body>
</html>
